package airthmetic.exercise.linkedList;

public class _2_两数相加 {
    //    输入：l1 = [2,4,3], l2 = [5,6,4]
    //    输出：[7,0,8]
    //    解释：342 + 465 = 807.
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry = 0;
        ListNode l3 = new ListNode(-1, null);
        ListNode res = l3;
        while (l1 != null || l2 != null){
            int value1 = l1 != null ? l1.val : 0;
            int value2 = l2 != null ? l2.val : 0;
            int num = (value1 + value2 + carry) % 10;
            carry = (value1 + value2 + + carry) / 10;

            l3.next = new ListNode(num,null);
            l1 = l1 != null ? l1.next : null;
            l2 = l2 != null ? l2.next : null;
            l3 = l3.next;
        }

        if (carry > 0){
            l3.next =  new ListNode(carry,null);
        }
        return res.next;
    }

    public static void main(String[] args) {
        ListNode listNode3 = new ListNode(3, null);
        ListNode listNode4 = new ListNode(4, listNode3);
        ListNode listNode2 = new ListNode(2, listNode4);

        ListNode listNode44 = new ListNode(4, null);
        ListNode listNode6 = new ListNode(6, listNode44);
        ListNode listNode5 = new ListNode(5, listNode6);

        ListNode returnListNode = addTwoNumbers(listNode2, listNode5);
        System.out.println(returnListNode);

    }
}
